# -*- coding: UTF-8 -*-
import json
from typing import List
from bean.hot_new import HotNew
from bean.hot_new_message import HotNewMessage
import requests
import numpy
import datetime


class WebPlatform:

    # url = "https://www.nicewebsite.cn/hot_news_web/news/save"
    url = "http://127.0.0.1:8080/hot_news_web/news/save"

    name: str

    def query_hot_news(self) -> List[HotNew]:
        pass

    def send(self):
        pass

    def execute(self):
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + self.name + " 开始查询")
        hot_news = self.query_hot_news()
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + self.name + " 查询完成")
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + self.name + " 开始上传")
        message: HotNewMessage = HotNewMessage(hot_news)
        response = requests.post(url=self.url, data=json.dumps({"message": message}, cls=HotNewsEncoder, indent=4))
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + self.name + " 上传结果" + str(response.content))


class HotNewsEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        elif isinstance(obj, HotNew):
            res = {}
            for f in dir(obj):
                value = getattr(obj, f)
                if not f.startswith("__") and not callable(value):
                    res[f] = value
        elif isinstance(obj, HotNewMessage):
            res = {}
            for f in dir(obj):
                value = getattr(obj, f)
                res_list = []
                if not f.startswith("__") and not callable(value):
                    for value_item in value:
                        res2 = {}
                        for ff in dir(value_item):
                            value2 = getattr(value_item, ff)
                            if not ff.startswith("__") and not callable(value2):
                                res2[ff] = value2
                        res_list.append(res2)
                    res[f] = res_list
            return res
        return json.JSONEncoder.default(self, obj)
